﻿#include "AbstractProcedure.h"
#include <QMetaEnum>
#include <QMetaObject>
#include <QNetworkReply>

namespace TC
{
    namespace Request
    {
        AbstractProcedure::AbstractProcedure(QObject *parent /*= nullptr*/)
            : QObject(parent)
        {
        }

        AbstractProcedure::~AbstractProcedure()
        {

        }

        AbstractProcedure::Status AbstractProcedure::status()
        {
            return _status;
        }

        QString AbstractProcedure::errorString()
        {
            return _errorString;
        }

        void AbstractProcedure::setReady()
        {
            _status = Status::Ready;
            statusChanged();
            ready();
        }

        void AbstractProcedure::setCommunicationing()
        {
            _status = Status::Communicating;
            statusChanged();
            communicationing();
        }

        void AbstractProcedure::setOk()
        {
            _status = Status::Ok;
            statusChanged();
            ok();
        }

        void AbstractProcedure::setFailed()
{
            _status = Status::Failed;
            statusChanged();
            failed();
        }

        void AbstractProcedure::setError(const QString &reason)
        {
            _errorString = reason;
            _status = Status::Error;
            statusChanged();
            error(reason);
        }

        void AbstractProcedure::autoSetHttpError(QNetworkReply::NetworkError code)
        {
            if (code == QNetworkReply::NetworkError::TimeoutError)
            {
                setError(QObject::tr("Failed to connect to server"));//"服务器连接失败啦！"
                return;
            }
            auto idx = QNetworkReply::staticMetaObject.indexOfEnumerator("NetworkError");
            setError(QString("Http Error : %1").arg(QNetworkReply::staticMetaObject.enumerator(idx).valueToKey(code)));
        }

        void AbstractProcedure::autoSetSocketError(QAbstractSocket::SocketError socketError)
        {
            if (socketError == QAbstractSocket::SocketError::SocketTimeoutError)
            {
                setError(QObject::tr("Failed to connect to server"));//"服务器连接失败啦！"
                return;
            }
            auto idx = QAbstractSocket::staticMetaObject.indexOfEnumerator("SocketError");
            setError(QString("Socket Error: %1").arg(QAbstractSocket::staticMetaObject.enumerator(idx).valueToKey(socketError)));
        }
		
		void AbstractProcedure::autoSetSslError(const QList<QSslError> &errors)
		{
			QString errorStrings;
			for (const QSslError &error : errors)
			{
				errorStrings += error.errorString() + '\n';
			}
			setError(QString(
				"Ssl Error (%1): \n"
				"%2"
			).arg(errors.size()).arg(errorStrings));
		}

	}
}
